//
//  CheckInView.m
//  playSerengetiMobile1
//
//  Created by Lita Gratrix on 11/10/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "CheckInView.h"
#import "CheckInPickerView.h"
#import "Location.h"
#import "Team.h"
#import "JSON/JSON.h"

#define COMPONANT_WIDTH 150.0
#define COMPONANT_HEIGHT -5
#define ROW_HEIGHT_FOR_COMPONANT 45

#define DEFAULT_INDEX 0


@implementation CheckInView

@synthesize nearbyLocations, teams;
@synthesize selectedLocation, selectedTeam;
@synthesize selectedLocationLabel, selectedTeamLabel;
@synthesize checkInPicker;
@synthesize locationController, appDelegate;

- (id)initWithTeams:(NSMutableArray *)teamsArg andLocations:(NSMutableArray *)nearbyLocationsArg{
	NSLog(@"Entering checkInView initWithTeams\n");
	[super init];

	self.teams = teamsArg;
	self.nearbyLocations = nearbyLocationsArg;
	NSLog(@"checkInView.teams has %d elements\n", [teams count]);
	NSLog(@"checkInView.nearbyLocations has %d elements\n", [nearbyLocations count]); 

	self.appDelegate = (playSerengetiMobile1AppDelegate *)[[UIApplication sharedApplication] delegate];
	
	if([nearbyLocations count] != 0){
		[self storeSelectedLocation:0];
	}
	
	if([teams count] != 0){
		[self storeSelectedTeam:0];
	}
	
	[self createPicker];
	
	return self;
}

- (void)checkInWithSelection:(id)sender{
	NSLog(@"Entering checkInWithSelection\n");
	NSLog(@"selectedteam is:%d, and selectedLocation is %d\n", selectedTeam, selectedLocation);
	NSString *URLString = [NSString stringWithFormat:@"%@user/checkIn?userId=%d&teamId=%d&locationId=%d", appDelegate.baseURL, appDelegate.loggedInAs, selectedTeam, selectedLocation];
	NSLog(@"String to submit checkin reads %@\n", URLString);
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
	[[NSURLConnection alloc] initWithRequest:request delegate:self];
	
}

/*
- (void) getNearbyLocations {
	NSLog(@"Entering getNearbyLocations\n");
	responseData = [[NSMutableData data] retain];
	NSString *URLString = [NSString stringWithFormat:@"%@location/getNearbyLocations?latitude=%f&longitude=%f", appDelegate.baseURL, latitude, longitude];
	NSLog(@"String to request nearby locations reads %@\n", URLString);
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
	nearbyLocationConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
*/

/*
#pragma mark -
#pragma mark Location Methods

- (void)getCurrentLocation{
	NSLog(@"Entering getCurrentLocation\n");
	if(TARGET_IPHONE_SIMULATOR){
		latitude = 33.969326;
		longitude = -118.414387;
		[self getNearbyLocations];
	} else {
		locationController = [[SerengetiCLController alloc] init];
		locationController.delegate = self;
		locationController.locationManager.desiredAccuracy =  LOCATION_ACCURACY;
		[locationController.locationManager startUpdatingLocation];
		[self performSelector:@selector(stopUpdatingLocation:) withObject:@"Timed Out" afterDelay:LOCATION_TIMEOUT];
	}
}

- (void)locationUpdate:(CLLocation *)location {
	NSLog(@"Entering locationUpdate.\n");
	NSLog(@"location is %@", location);
	NSLog(@"location.coordinate.latitude = %f\n", location.coordinate.latitude);
	self.latitude = location.coordinate.latitude;
	NSLog(@"self.latitude = %f\n", self.latitude);
	self.longitude = location.coordinate.longitude;	
	[self getNearbyLocations];
}

- (void)locationError:(NSError *)error {
	NSLog(@"Error capturing locaiton: %@", [error description]);
}
		
- (void)stopUpdatingLocation:(NSString *)state {
	[locationController.locationManager stopUpdatingLocation];
	locationController.locationManager.delegate = nil;
}
*/		

#pragma mark -
#pragma mark CheckInVariable Methods
- (void)storeSelectedTeam:(NSInteger)index{
	NSLog(@"storeSelectedTeam for index %d\n", index);
	Team *team = [[Team alloc] init];
	team = [teams objectAtIndex:index];
	if(team != nil){
		selectedTeam = team.teamId;
		selectedTeamLabel.text = team.teamName;
	}
//	[team release];
//	team = nil;
	NSLog(@"selectedTeam is %d\n", team.teamId);
}

- (void)storeSelectedLocation:(NSInteger)index{
	NSLog(@"storeSelectedLocation for index %d\n", index);
	Location *location = [[Location alloc] init];
	location = [nearbyLocations objectAtIndex:index];
	if(location != nil){
		selectedLocation = location.locationId;
		selectedLocationLabel.text = location.locationName;
	}
//	[location release];
//	location = nil;
	NSLog(@"selectedLocation is %d\n", location.locationId);	
}

#pragma mark -
#pragma mark NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
		NSLog(@"Connection to check in failed: %@\n", [error description]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
		[connection release];
		
		NSLog(@"Succeeded! Received %d bytes of data\n",[responseData length]);  
		NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
		NSLog(@"responseString for checkinConnection reads: %@\n", responseString);
		
		[appDelegate loadMainView];
}	

/*
- (void) populateNearbyLocations:(NSDictionary *)parsedData {
	NSLog (@"Entering populate Nearby Locations.\n");
	NSMutableArray *locationsArray = [parsedData objectForKey:@"locations"];
	NSLog(@"locationsArray has %d elements\n", [locationsArray count]);
	if([locationsArray count] == 0){
		//Do something
	}else{
		[nearbyLocations removeAllObjects];
		int i;
		for(i = 0; i < [locationsArray count]; i++){
			//NSLog(@"creating location for index %d\n", i);
			Location *location = [[Location alloc] init];
			NSDictionary *locationDic = [locationsArray objectAtIndex:i];
			location.locationId = [[locationDic objectForKey:@"id"] integerValue];
			location.locationName = [locationDic objectForKey:@"name"];
			location.phoneNumber = [locationDic objectForKey:@"phoneNumber"];
			location.latitude = [[locationDic objectForKey:@"latitude"] doubleValue];
			location.longitude = [[locationDic objectForKey:@"longitude"] doubleValue];
			location.street = [locationDic objectForKey:@"street"];
			location.city = [locationDic objectForKey:@"city"];
			location.state = [locationDic objectForKey:@"state"];
			location.zipCode = [locationDic objectForKey:@"zipcode"];
			location.description = [locationDic objectForKey:@"description"];
			NSDictionary *teamDic = [locationDic objectForKey:@"owner"];
			location.teamOwner = [self populateTeamOwner:(NSDictionary *)teamDic];
			NSLog(@"created location that looks like [%d, %@, %f, %f,", location.locationId, location.locationName, location.latitude, location.longitude);
			NSLog(@"%@, %@, %@, %@, %@,", location.phoneNumber, location.street, location.city, location.state, location.zipCode);
			NSLog(@"%@, {%d, %@}]\n", location.description, location.teamOwner.teamId, location.teamOwner.teamName);
			[nearbyLocations addObject: location];
		}
		NSLog(@"nearbyLocations has %d objects", [nearbyLocations count]);
	}
	
}

- (Team *)populateTeamOwner:(NSDictionary *)teamDic{
//	NSLog(@"Entering populateTeamOwner\n");
	Team *teamOwner = [[Team alloc] init];
	teamOwner.teamId = [[teamDic objectForKey:@"id"] integerValue];
	teamOwner.teamName = [teamDic objectForKey:@"name"];
//	NSLog(@"Returning teamOwner that looks like: [%d , %@]\n", teamOwner.teamId, teamOwner.teamName);
	return teamOwner;
}
*/ 
 
 
#pragma mark -
#pragma mark Picker Methods

- (CGRect)pickerFrameWithSize:(CGSize)size{
	CGRect screenRect = [[UIScreen mainScreen] applicationFrame];
	CGRect pickerRect = CGRectMake(	0.0,
								   screenRect.size.height - COMPONANT_HEIGHT- size.height,
								   size.width,
								   size.height);
	return pickerRect;
}


- (void)createPicker{
	NSLog(@"Entering createPicker\n");
	
	// note we are using CGRectZero for the dimensions of our picker view,
	// this is because picker views have a built in optimum size,
	// you just need to set the correct origin in your view.
	//
	// position the picker at the bottom
	checkInPicker = [[UIPickerView alloc] initWithFrame:CGRectZero];
	CGSize pickerSize = [checkInPicker sizeThatFits:CGSizeZero];
	checkInPicker.frame = [self pickerFrameWithSize:pickerSize];
	
	checkInPicker.autoresizingMask = UIViewAutoresizingFlexibleWidth;
	checkInPicker.showsSelectionIndicator = YES;	// note this is default to NO
	
	// this view controller is the data source and delegate
	checkInPicker.delegate = self;
	checkInPicker.dataSource = self;
	
	// add this picker to our view controller, initially hidden
	checkInPicker.hidden = NO;
	NSLog(@"Picker Ready in checkInPicker\n");
	[self.view addSubview:checkInPicker];
	NSLog(@"Exiting checkInPicker\n");
}


#pragma mark -
#pragma mark UIPickerViewDelegate

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	NSLog(@"Entering pickerView didSelectRow\n");
	NSLog(@"Row is currently %d\n", row);
	if(component == 0){
		//if(row < [nearbyLocations count]){
			//Location *aLocation = [[Location alloc] init];
			//aLocation = [nearbyLocations objectAtIndex:row];
			//NSLog(@"nearbyLocations objectAtIndex:%d is\n", row, tempString);
			//NSLog(@"aLocation is currently %@\n", aLocation.locationName);
			[self storeSelectedLocation:row];
			//[aLocation release];
		//}
	}else if (component == 1){
		//if(row < [teams count]){
			//Team *aTeam = [teams objectAtIndex:row];
			[self storeSelectedTeam:row];
			//[aTeam release];
		//}
	}
}

// tell the picker which view to use for a given component and row, we have an array of views to show
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row
		  forComponent:(NSInteger)component reusingView:(UIView *)view{
	NSLog(@"Entering viewForRow: %d ForComponent\n", row);
	CheckInPickerView *aCheckInPickerView = [[CheckInPickerView alloc] initWithFrame:CGRectZero];
	if(component == 0){
		NSLog(@"row in viewForRow is %d\n", row);
		Location *aLocation = [nearbyLocations objectAtIndex:row];
		aCheckInPickerView.title = aLocation.locationName;
//		[aLocation release];
//		aLocation = nil;
	}else if (component == 1){
		NSLog(@"teams has %d elements\n", [teams count]);
		Team *aTeam = [teams objectAtIndex:row];
		aCheckInPickerView.title = aTeam.teamName;
//		[aTeam release];
//		aTeam = nil;
	}
	return aCheckInPickerView;
}

#pragma mark -
#pragma mark UIPickerViewDataSource

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
	CGFloat componentWidth = 0.0;
	
	if (component == 0)
		componentWidth = [CheckInPickerView viewWidth];	
	else
		componentWidth = [CheckInPickerView viewWidth];	
	return componentWidth;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
	return [CheckInPickerView viewHeight];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	if(component == 0){
		return [nearbyLocations count];
	} else {
		return [teams count];
	}
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 2;
}


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[locationController release];
    [super dealloc];
}


@end
